#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import json
import os

from common.common import get_host_sn
from common.common_models import SubJobDetails
from common.parse_parafile import ParamFileUtil
from exchange import log
from exchange.commons.common import output_execution_result_ex
from exchange.commons.const import ExchangeJobInfo, SubJobStatusEnum, ParamConstant
from exchange.commons.exchange_function_tool import log_start_end, get_progress_file_name
from exchange.commons.exchange_param_parse import ExchangeParamParse


# Exchange备份查询任务进度基类
class ExchangeBackupQueryProgress:
    def __init__(self, pid):
        self._pid = pid
        self._param = ParamFileUtil.parse_param_file(pid)

    @log_start_end()
    def do_query_progress_task(self, job_info: ExchangeJobInfo):
        log.info(f"do query progress task  job_id: {job_info.job_id} ,sub_job_id : {job_info.sub_job_id}")
        # 默认查询common进度文件
        file_name = get_progress_file_name(job_info)
        cache_path = ExchangeParamParse.get_cache_path(self._param)
        file_path_comm = os.path.join(cache_path, file_name)
        try:
            if os.path.exists(file_path_comm):
                log.info(f"File exist.")
                with open(file_path_comm, mode='r') as f:
                    json_str = json.loads(f.read())
            else:
                log.info(f"File not exist!")
                if os.path.exists(cache_path):
                    # 父目录还存在，说明任务没跑完，还没解挂，反RUNNING
                    json_str = SubJobDetails(taskId=job_info.job_id, subTaskId=job_info.sub_job_id, progress=5,
                                             logDetail=list(), taskStatus=SubJobStatusEnum.RUNNING.value).dict(
                        by_alias=True)
                else:
                    # 父目录不存在，说明任务已经结束，FS已经解挂，不能反RUNNING，会导致数据库框架死循环
                    json_str = SubJobDetails(taskId=job_info.job_id, subTaskId=job_info.sub_job_id, progress=5,
                                             logDetail=list(), taskStatus=SubJobStatusEnum.COMPLETED.value).dict(
                        by_alias=True)
        except Exception as err:
            log.error(f"Failed to read progress file as err: {err}")
            json_str = SubJobDetails(taskId=job_info.job_id, subTaskId=job_info.sub_job_id, progress=5,
                                     logDetail=list(), taskStatus=SubJobStatusEnum.FAILED.value).dict(by_alias=True)
        file_path = os.path.join(ParamConstant.RESULT_PATH, f"result{job_info.pid}")
        output_execution_result_ex(file_path, json_str)
        return True

    def get_job_info(self):
        job_info = ExchangeJobInfo(pid=self._pid,
                                   job_id=ExchangeParamParse.get_job_id(self._param),
                                   sub_job_id=ExchangeParamParse.get_sub_job_id(self._param),
                                   copy_id=ExchangeParamParse.get_copy_id(self._param),
                                   backup_type=ExchangeParamParse.get_type(self._param),
                                   meta_path=ExchangeParamParse.get_meta_path(self._param),
                                   data_reps=ExchangeParamParse.get_data_reps(self._param),
                                   cache_path=ExchangeParamParse.get_cache_path(self._param),
                                   backup_result=ExchangeParamParse.get_backup_result(self._param))
        return job_info
